import React, { useEffect, useState, useContext } from "react"
import { View, Image, Button, Navigator } from "@tarojs/components"
import { navigateTo } from "@tarojs/taro"
import "./mine.scss"
import { useDidShow, getStorageSync, removeStorageSync } from "@tarojs/taro"
import service from "@@/services/user.service"
import NavLayout from "@@/components/layout/nav.layout"

const MinePage = () => {
  const [logStatus, setLogStatus] = useState<boolean>(false)//当前tab值
  const [name, setName] = useState<string>("")//用户名

  useDidShow(() => {
    //判断h5端是否登录
    if (TARO_ENV === "h5") {
      if (getStorageSync("token")) {
        setLogStatus(true)
        service.getUserInfo().then(res => {
          if (res.code === 200) {
            const data = res.data;
            setName(data.name);
          }
        })
      }
    }
  })

  const getPhoneNumber = (e) => {
    console.log(e.detail.rawData)
    console.log(e)
  }
  //去登录
  const goLogin = () => {
    if (TARO_ENV === "h5") {
      navigateTo({
        url: "/pages/login/login"
      })
    }
  }
  //退出登录
  const logout = () => {
    if (TARO_ENV === "h5") {
      removeStorageSync("token");
      window.location.reload();
    }
  }

  const entrances = (url: string) => () => {
    if (TARO_ENV === "h5") {
      if (getStorageSync("token")) {
        navigateTo({
          url: `/pages/${url}`
        })
      } else {
        navigateTo({
          url: "/pages/login/login"
        })
      }
    }
  }
  return <NavLayout border title='我的' leftIconType="chevron-left" color="#141414" id="MinePage">
    <View className='header'>
      <View className='headBox'>
        <Image src={require("@@/assets/img/head-icon.png")}></Image>
      </View>
      {
        logStatus ? <View>
          <View className={"user"}>{name}</View><View className='headerText'>Hi！欢迎您回来</View>
        </View>
          : <View>
            <Button openType="getUserInfo" onClick={goLogin} className='loginBtn' onGetPhoneNumber={getPhoneNumber} >立即登录</Button>
            <View className='headerText'>登录后，查看更多展会信息</View>
          </View>
      }

    </View>
    <View className="mineList">
      <Navigator onClick={entrances("userinfo/userinfo")} className="mineItem">
        <View className="icon">
          <Image src={require("@@/assets/img/userinfo.png")}></Image>
        </View>
        <View className="text">个人信息</View>
        <View className="arrow">
          <Image src={require("@@/assets/img/arrow-right.png")}></Image>
        </View>
      </Navigator>
    </View>
    {
      logStatus && <Button openType="getUserInfo" onClick={logout} className='logoutBtn' >退出登录</Button>
    }
  </NavLayout>
}
export default MinePage
